java当我尝试打印所有组时,得到“IndexOutOfBoundsException:无组4”
我的代码是
String regexpr = "(abc)(ab)(cd)";
String test = "abcabcd";
Pattern p = Pattern.compile(regexpr);
Matcher m = p.matcher(test);
while(m.find ())
{
System.out.println(m.group());
}
此代码将输出为
^{pr2}$但我想打印匹配字符串中的所有组,即
group 1 abc
group 2 ab
group 3 cd
我试过这个
int i=1;
while (m.group(i) != null)
{
System.out.println("group" + i + m.group(i));
i++;
}
我要走了
group 1 abc
group 2 ab
group 3 cd
Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 4
我怎样才能避免这个例外
如何打印所有组的开始索引和结束索引
# 1 楼答案
您可以按以下方式打印所有组的开始索引和结束索引:
# 2 楼答案
问题是当
i
增加到4时,您仍在检查:但没有这样的第四组
一种解决方案是使用^{} :